package com.lagou.boot;

import com.alibaba.fastjson.JSONObject;
import com.lagou.client.RPCConsumer;
import com.lagou.service.IUserService;
import com.lagou.service.RpcRequest;
import io.netty.handler.codec.json.JsonObjectDecoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class ConsumerBoot {
    private static List<String> servers = new LinkedList<String>();

    public static void main(String[] args) throws InterruptedException {

        while (true){
            //1.创建代理对象
            try {
                String server = pullZookeeper();
                if(!server.isEmpty()){
                    IUserService service = (IUserService) RPCConsumer.createProxy(IUserService.class,
                            server);
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setMethodName("sayHello");
                    rpcRequest.setParameter("are you ok !!");
                    String msg = JSONObject.toJSONString(rpcRequest);
                    String result = service.sayHello(msg);
                    System.out.println(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(2000);
        }

    }

    private static String pullZookeeper() throws Exception {
        String res = "";
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 1);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("rpc")  // 独立的命名空间 /base
                .build();

        client.start();

        String path = "/server";
        List<String> servers = client.getChildren().forPath(path);
        System.out.println("pull servers：" + servers);
        long ptr = Long.MIN_VALUE;
        for(String server:servers){
            Stat stat = new Stat();
            client.getData().storingStatIn(stat).forPath(path+"/"+server);
            if(stat.getMtime()>ptr){
                ptr = stat.getMtime();
                res = server;
            }
        }

        return res;
    }
}
